package com.leo.util;

import com.leo.model.Node;

/**
 * @ClassName NodeUtil
 * @Description
 * @Author wangss
 * @date 2022.01.28 18:06
 * @Version 1.0
 */
public class NodeUtil {

    /**
     * 展示链表信息
     *
     * @param head
     */
    public static void showNode(Node head) {
        StringBuilder sb = new StringBuilder();
        while (null != head) {
            sb.append(head.data);
            if (null != head.next) {
                sb.append(" -> ");
            }
            head = head.next;
        }
        System.out.println(sb.toString());
    }

    /**
     * 遍历的方式实现单链表反转
     *
     * @param head
     * @return
     */
    public static Node reverseIterativel(Node head) {
        // 上一个节点
        Node pre = null;
        // 下一个节点
        Node next = null;

        while (null != head) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
            showNode(pre);
        }
        return pre;
    }

    /**
     * 使用递归的方式进行单链表反转
     *
     * @param head
     * @return
     */
    public static Node reverse(Node head) {
        if (null == head || null == head.next) {
            return head;
        }
        Node next = head.next;
        Node reverse = reverse(next);
        next.next = head;
        head.next = null;
        return reverse;
    }
}
